package com.trace.app.util;

import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author : lyj
 * @Timer : 2024/5/1
 * @Description :
 */
public class InputStreamToPathUtil {

    @SneakyThrows
    public static Path convert(InputStream inputStream) {

        // 将InputStream写入到临时文件中
        File tempFile = File.createTempFile("temp", ".tmp");
        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        // 使用临时文件的路径创建一个Path对象
        Path path = Paths.get(tempFile.toURI());

        // 现在你可以使用这个Path对象了
        System.out.println("Path: " + path);
        return path;
    }

    public static void main(String[] args) throws IOException {
        InputStream is = new ClassPathResource("classpath:/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/msp/signcerts/User1@org1.example.com-cert.pem").getInputStream();
        Path path = InputStreamToPathUtil.convert(is);
        System.out.println("Path: " + path);
    }
}
